/* eslint no-underscore-dangle: 0 */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Button, Table, Pagination, Icon, Message, Input, Select, Grid, Dialog, Checkbox } from '@alifd/next';
import IceContainer from '@icedesign/container';
import request from '../../../../instances/request';
import {
  FormBinderWrapper as IceFormBinderWrapper,
  FormBinder as IceFormBinder,
  FormError as IceFormError,
} from '@icedesign/form-binder';
import FoundationSymbol from '@icedesign/foundation-symbol';
import { noteTypes } from '../../../../conf/noteTypeConfig';
import { browsePrivilegesConfig } from '../../../../conf/privilegesConfig';
import UserControlFormDialog from './UserControlFormDialog';

const { Row, Col } = Grid;

// todo: 为什么Dialog里面不用React class就不会正常根据state刷新？
class ApprovalPrivilegesForm extends Component {
  static defaultProps = {
    approvalPrivileges: [],
    transChange: () => {},
  };

  constructor(props){
    super(props);

    this.state = {
      approvalPrivileges: this.props.approvalPrivileges,
      tableWidth: 800,
    }
  }

  onTypeChange(idx, type) {
    let approvalPrivileges = this.state.approvalPrivileges;
    approvalPrivileges[idx].type = type;
    approvalPrivileges[idx].step = null;
    this.setState({
      approvalPrivileges
    });
    this.props.transChange(approvalPrivileges);
  }

  onStepChange(idx, step) {
    let approvalPrivileges = this.state.approvalPrivileges;
    approvalPrivileges[idx].step = step;
    this.setState({
      approvalPrivileges
    });
    this.props.transChange(approvalPrivileges);
  }

  render() {
    return (
      <div style={{ width: '600px' }}>
        {
          this.state.approvalPrivileges.map((ele, idx) => {
            let steps = [];
            noteTypes.forEach((e, i) => {
              if( ele.type === e.enName ) {
                steps = e.steps;
              }
            });
            return (
              <div key={idx} style={styles.formItem}>
                <div style={styles.formLabel}>审批权限</div>
                <Select
                  onChange={this.onTypeChange.bind(this, idx)}
                  style={{ width: '200px' }}
                  value={ele.type}
                  dataSource={
                    noteTypes.map((e) => {
                      return {
                        value: e.enName,
                        label: e.name,
                      }
                    })
                  }
                />
                <Select
                  value={ele.step}
                  onChange={this.onStepChange.bind(this, idx)}
                  style={{ width: '200px', 'marginLeft': '10px', }}
                  dataSource={steps}
                />
                <span
                  onClick={() => {
                    let approvalPrivileges = this.state.approvalPrivileges;
                    approvalPrivileges.splice(idx, 1);
                    this.setState({
                      approvalPrivileges
                    });
                    this.props.transChange(approvalPrivileges);
                  }}
                  title="删除"
                  style={styles.operBtn}
                >
                  <Icon size="xxs" type="close" />
                </span>
              </div>
            )
          })
        }
        <div style={{ textAlign: 'center' }}>
          <Button
            type="secondary"
            onClick={() => {
              let approvalPrivileges = this.state.approvalPrivileges;
              approvalPrivileges.push({
                type: 'Construction',
                step: 1,
              });
              this.setState({
                approvalPrivileges
              });
              this.props.transChange(approvalPrivileges);
            }}
          >添加一项审批权限</Button>
        </div>
      </div>
    )
  }
}

export default class UserControlOperationTable extends Component {
  static displayName = 'UserControlOperationTable';

  static propTypes = {
    limit: PropTypes.number,
  };

  static defaultProps = {
    limit: 8
  };

  constructor(props) {
    super(props);
    this.state = {
      value: {
        sTeamName: 'all',
      },
      tableData: {
        totalCount: 0,
        pageSize: this.props.limit,
        currentPage: 1,
        list: [],
        __loading: true,
      },
      browsePrivileges: {  // 用户浏览权限
        dashboardView: false,  // 首页通知浏览权限
        dashboardEdit: false,   // 首页通知编辑权限
        workingScheduleView: false,  // 排班表浏览权限
        workingScheduleEdit: false,  // 排班表编辑权限
        dutyShiftView: false,  // 交接班记录浏览权限
        dutyShiftEdit: false, // 交接班记录编辑权限
        inspectionListView: false, // 巡视检查单浏览权限
        inspectionSupport: false, // 博维Support确认权限（是否是博维Support人员）
        requestNoteView: false, // 申请权限
        approvalListView: false, // 审批权限
        equipmentControlView: false, // 设备管理权限
        userControlView: false, // 用户管理权限
        groupControlView: false, // 部门管理权限
        settingsView: false, // 个人设置权限
      },
      approvalPrivileges: [], // 用户审批权限
    };
  }

  async addOrUpdateUser({ id, username, password, isTeamLeader, GroupId, teamname, phone, email, description }) {
    let url = id == null || id === undefined ? '/superuser/user/add' : '/superuser/user/update';
    let res = await request.post(url,{
      id,
      username,
      password,
      teamname,
      isTeamLeader,
      GroupId,
      phone,
      email,
      description,
    }).catch((err) => {
      Message.error(`添加或更新用户接口${err}`);
      return Promise.reject(err);
    });

    let { code, msg } = res.data;
    switch (code) {
      case 0:
        await this.fetchData({ page: this.state.tableData.currentPage });
        break;
      default:
        Message.error(msg.error);
        return msg.error;
    }
  }

  async deleteUser({ id }) {
    let res = await request.post('/superuser/user/delete', {
      id,
    }).catch((err) => {
      Message.error(`删除用户接口${err}`);
      return Promise.reject((err));
    });
    console.log("删除用户接口",res);

    let { code, msg } = res.data;
    switch (code) {
      case 0:
        await this.fetchData({ page: this.state.tableData.currentPage });
        break;
      default:
        Message.error(msg.error);
        break;
    }
  }

  async fetchData ({ page }) {
    const tableData = this.state.tableData;
    tableData.__loading = true;

    this.setState({ tableData }, async function() {
      let res = await request.post('/superuser/user/list', {
        limit: this.props.limit,
        page: page,
        sTeamName: this.state.value.sTeamName,
        sStr: this.state.value.sStr,
      }).catch((err) => {
        Message.error(`用户管理列表接口${err}`);
        return Promise.reject(err);
      });

      console.log("用户管理列表接口", res);

      let { code, msg } = res.data;
      switch (code) {
        case 0:
          let { userList, totalCount, count } = msg;
          const tableData = this.state.tableData;
          tableData.list = userList;
          tableData.totalCount = totalCount;
          tableData.__loading = false;
          this.setState({
            tableData
          });
          break;
        default:
          Message.error(`用户管理列表接口code${code}`);
          break;
      }
    });
  };

  hookUserControlFormDialog(value) {
    console.log(value);
    value = value || {
      isTeamLeader: false,
    };
    UserControlFormDialog.show({
      value: value,
      onOk: (value) => {
        // 添加数据
        return this.addOrUpdateUser({
          id: value.id,
          username: value.username,
          password: value.password,
          isTeamLeader: value.isTeamLeader,
          GroupId: value.GroupId,
          teamname: value.teamname,
          phone: value.phone,
          email: value.email,
          description: value.description,
        }).then((error) => {
          if( error ) {
            Message.error(error);
          } else {
            value.id ? Message.success("修改用户成功") : Message.success('添加用户成功');
            UserControlFormDialog.hide();
          }
        });
      },
      onClose: () => {
        UserControlFormDialog.hide();
      },
      onCancel: () => {
        UserControlFormDialog.hide();
      },
    });
  }

  editItem = (record, e) => {
    e.preventDefault();
    this.hookUserControlFormDialog(record);
  };

  startItem = (record, e) => {
    e.preventDefault();

    let dialog = Dialog.confirm({
      title: '启用确认',
      content: '您确认启用此用户吗？',
      onOk: () => {
        return request
          .post('/superuser/user/start', { id: record.id })
          .then(() => {
            dialog.hide();
            Message.success("启用成功");
            return this.fetchData({ page: this.state.tableData.currentPage });
          });
      },
      onCancel: () => {
        dialog.hide();
      },
      onClose: () => {
        dialog.hide();
      }
    });
  };

  stopItem = (record, e) => {
    e.preventDefault();

    let dialog = Dialog.confirm({
      title: '停用确认',
      content: '您确认停用此用户吗？',
      onOk: () => {
        return request
          .post('/superuser/user/stop', { id: record.id })
          .then(() => {
            dialog.hide();
            Message.success("停用成功");
            return this.fetchData({ page: this.state.tableData.currentPage });
          });
      },
      onCancel: () => {
        dialog.hide();
      },
      onClose: () => {
        dialog.hide();
      }
    });
  };

  deleteItem = (record, e) => {
    e.preventDefault();

    let dialog = Dialog.confirm({
      title: '删除确认',
      content: '您确认删除此用户吗？',
      onOk: () => {
        return this.deleteUser({ id: record.id }).then(() => {
          dialog.hide();
          Message.success("删除成功");
        });
      },
      onCancel: () => {
        dialog.hide();
      },
      onClose: () => {
        dialog.hide();
      }
    });
  };

  onBrowsePrivilegeChange(browsePrivileges) {
    this.setState({
      browsePrivileges,
    });
  }


  // todo: 想要用这个全选，就必须创建一个真正的React类
  // selectAllBrowse(checked) {
  //   let browsePrivileges = {};
  //
  //   if(checked) {
  //     Object.keys(this.state.browsePrivileges).map((key) => {
  //       if(key !== 'id' && key !== 'createdAt' && key !== 'updatedAt') {
  //         browsePrivileges[key] = true;
  //       } else {
  //         browsePrivileges[key] = this.state.browsePrivileges[key];
  //       }
  //     });
  //   } else {
  //     Object.keys(this.state.browsePrivileges).map((key) => {
  //       if(key !== 'id' && key !== 'createdAt' && key !== 'updatedAt') {
  //         browsePrivileges[key] = false;
  //       } else {
  //         browsePrivileges[key] = this.state.browsePrivileges[key];
  //       }
  //     });
  //   }
  //
  //   this.setState({
  //     browsePrivileges,
  //   });
  // }

  setBrowsePrivilege(user) {
    this.setState({
      browsePrivileges: user.browsePrivileges || {},
    }, () => {
      let { id } = user;
      let dialog = Dialog.show({
        isFullScreen: true,
        shouldUpdatePosition: true,
        title: '设置用户浏览权限',
        content: (
          <IceFormBinderWrapper
            // todo : 这里value={} 可以刷新组件的显示
            value={this.state.browsePrivileges}
            // todo: 这里onChange里面setState，无法刷新组件的显示
            // todo: 因为这个Dialog.show函数在父组件外面创建了这个Dialog组件（直接往Dom里面插入），所以无法根据正常的父组件的state变化而变化
            // todo: 解决方案：利用DialogDecorator新建一个Dialog类，在那个类里面进行操作
            // onChange={this.onBrowsePrivilegeChange.bind(this)}
          >
            <div style={{ padding: '0px 40px' }}>
              {/*// todo: 想要用这个全选，就必须创建一个真正的React类 */}
              {/*<div style={styles.formItem}>*/}
                {/*<Checkbox label='全选' onChange={this.selectAllBrowse.bind(this)}/>*/}
              {/*</div>*/}
              {
                browsePrivilegesConfig.map((ele, idx) => {
                  return (
                    <div key={idx} style={styles.formItem}>
                      <IceFormBinder
                        name={ele.enName}
                      >
                        <Checkbox
                          label={ele.cnName}
                          defaultChecked={this.state.browsePrivileges[ele.enName]}
                        />
                      </IceFormBinder>
                    </div>
                  )
                })
              }
            </div>
          </IceFormBinderWrapper>
        ),
        onOk: () => {
          return request
            .post('/superuser/privilege/set', {
              id,
              browsePrivileges: this.state.browsePrivileges
            }).then((res) => {
              let { code, msg } = res.data;
              if( code !== 0 ) {
                throw new Error(`code为${code}`);
              }
              Message.success('设置用户浏览权限成功');
              this.fetchData({
                page: this.state.tableData.currentPage
              }).then(() => {
                dialog.hide();
              });
            });
        },
        onCancel: () => {
          dialog.hide();
        }
      });
    });
  }

  setApprovalPrivilege(user) {
    this.setState({
      approvalPrivileges: user.approvalPrivileges || [],
    }, () => {
      let { id } = user;
      let dialog = Dialog.show({
        shouldUpdatePosition: true,
        isFullScreen: true,
        title: '设置用户审批权限',
        content: (
          <ApprovalPrivilegesForm
            approvalPrivileges={this.state.approvalPrivileges}
            transChange={(approvalPrivileges) => {
              this.setState({
                approvalPrivileges
              })
            }}
          />
        ),
        onOk: () => {
          return request
            .post('/superuser/approval/set', {
              id,
              approvalPrivileges: this.state.approvalPrivileges,
            }).then((res) => {
            let { code, msg } = res.data;
            if( code !== 0 ) {
              throw new Error(`code为${code}`);
            }
            Message.success('设置用户审批权限成功');
            this.fetchData({
              page: this.state.tableData.currentPage
            }).then(() => {
              dialog.hide();
            });
          });
        },
        onCancel: () => {
          dialog.hide();
        }
      });
    });
  }

  renderOperations = (value, index, record) => {
    return (
      <div>
        <div>
          <span
            style={{ color: 'rgba(49, 128, 253, 0.65)', cursor: 'pointer' }}
            onClick={ this.editItem.bind(this, record) }
          >
            编辑
          </span>
          <span style={styles.separator}/>
          {
            record.isStop ?
              <span
                style={{ color: 'rgba(49, 128, 253, 0.65)', cursor: 'pointer' }}
                onClick={ this.startItem.bind(this, record) }
              >
            启用
          </span> :
              <span
                style={{ color: 'rgba(49, 128, 253, 0.65)', cursor: 'pointer' }}
                onClick={ this.stopItem.bind(this, record) }
              >
            停用
          </span>
          }
          <span style={styles.separator}/>
          <span
            style={{ color: 'rgba(49, 128, 253, 0.65)', cursor: 'pointer' }}
            onClick={ this.deleteItem.bind(this, record) }
          >
            删除
          </span>
        </div>
        {/*<div style={{ marginTop: '5px' }}>*/}
          {/*<span*/}
            {/*style={{ color: 'rgba(49, 128, 253, 0.65)', cursor: 'pointer' }}*/}
            {/*onClick={ this.setBrowsePrivilege.bind(this, record) }*/}
          {/*>*/}
            {/*设置浏览权限*/}
          {/*</span>*/}
        {/*</div>*/}
        <div style={{ marginTop: '5px' }}>
          <span
            style={{ color: 'rgba(49, 128, 253, 0.65)', cursor: 'pointer' }}
            onClick={ this.setApprovalPrivilege.bind(this, record) }
          >
            设置审批权限
          </span>
        </div>
      </div>
    );
  };

  renderApprovalPrivilege = (value, index, record) => {
    let approvalPrivilege = record.approvalPrivileges || [];
    return (
      <div style={{ height: '40px', lineHeight: '40px', overflowY: 'auto' }}>
        <div style={{ lineHeight: '20px', display:'inline-block', verticalAlign: 'middle' }}>
        {
          approvalPrivilege.map((ele, idx) => {
            let approver = '';
            let type = '';
            noteTypes.forEach((note, i) => {
              if (note.enName === ele.type) {
                type = note.name;
                note.steps.forEach((s) => {
                  if (s.value === ele.step) {
                    approver = s.label;
                  }
                });
              }
            });
            return (
              <div key={idx}>{type}-{approver}</div>
            )
          })
        }
        </div>
      </div>
    )
  };

  changePage = (currentPage) => {
    const tableData = this.state.tableData;
    tableData.currentPage = currentPage;
    this.setState({
      tableData
    });
    return this.fetchData({ page: currentPage });
  };

  addUser = () => {
    this.hookUserControlFormDialog();
  };

  async componentDidMount() {
    this.setState({
      tableWidth: document.body.clientWidth - 290 + 40 + 15,
    });
    await this.fetchData({
      page: 1
    });
  }

  onFormChange(value) {
    // console.log(value);
  }

  render() {
    const tableData = this.state.tableData;

    return (
      <div className="operation-table">
        <IceContainer style={styles.cardContainer}>
          <Row>
            <Col>
              <div style={{ height: '60px', background: '#EAEBEF' }}>
                <div style={
                  {
                    float: 'left',
                    fontSize: '20px',
                    fontWeight: 'bold',
                    height: '60px',
                    lineHeight: '60px',
                    paddingLeft: '30px',
                  }
                }>
                  <FoundationSymbol type='person' style={{ display: 'inline', verticalAlign: 'middle' }}/>
                  <span>&nbsp;用户管理</span>
                </div>
                <div style={
                  {
                    height: '60px',
                    lineHeight: '60px',
                    marginRight: '20px',
                    float: 'right',
                  }
                }
                >
                  <Button style={styles.addButton} type='primary' onClick={this.addUser}>添加用户</Button>
                </div>
              </div>
            </Col>
          </Row>
          <Row>
            <Col>
              <div style={{ paddingLeft: '20px' }}>
                <IceFormBinderWrapper
                  value={this.state.value}
                  onChange={this.onFormChange.bind(this)}
                  ref="form"
                >
                  <Row>
                    <Col span={6}>
                      <div style={styles.formItem}>
                        <div style={styles.formLabel}>搜索：</div>
                        <IceFormBinder
                          name="sStr"
                        >
                          <Input
                            onPressEnter={this.fetchData.bind(this, { page: 1})}
                            placeholder="请输入"
                            trim={true}
                          />
                        </IceFormBinder>
                      </div>
                    </Col>
                    <Col span={6}>
                      <div style={styles.formItem}>
                        <div style={styles.formLabel}>班组：</div>
                        <IceFormBinder
                          name="sTeamName"
                        >
                          <Select size="medium"  style={{ width: '220px' }}>
                            {
                              ['A组', 'B组', 'C组', 'D组', '无'].map((ele, idx) => {
                                return <Select.Option key={idx} value={ele}>{ele}</Select.Option>;
                              })
                            }
                            <Select.Option value={'all'}>
                              全部
                            </Select.Option>
                          </Select>
                        </IceFormBinder>
                      </div>
                    </Col>
                    <Col span={3}>
                      <div style={styles.formItem}>
                        <Button
                          type='primary'
                          onClick={this.fetchData.bind(this, { page: 1})}
                        >查询</Button>
                      </div>
                    </Col>
                  </Row>
                </IceFormBinderWrapper>
              </div>
            </Col>
          </Row>
          <div style={{ width: this.state.tableWidth }}>
            <Table
              isZebra={true}
              dataSource={tableData.list}
              loading={tableData.__loading}
              className="basic-table"
              hasBorder={false}
              primaryKey="key"
              style={{ padding: '0 20px 20px' }}
            >
              <Table.Column
                lock
                title="登录名"
                dataIndex="username"
                width={100}
              />
              <Table.Column
                title="审批权限"
                width={300}
                cell={this.renderApprovalPrivilege}
              />
              <Table.Column
                title="所属部门"
                dataIndex="groupname"
                width={120}
              />
              <Table.Column
                title="Id"
                dataIndex="id"
                width={60}
              />
              <Table.Column
                title="状态"
                dataIndex="isStop"
                width={150}
                cell={(value, index, row) => {
                  return row.isStop ? '已停用' : '正常';
                }}
              />
              <Table.Column
                title="所属班组"
                dataIndex="teamname"
                width={150}
              />
              <Table.Column
                title="手机号"
                dataIndex="phone"
                width={200}
              />
              <Table.Column
                title="邮箱"
                dataIndex="email"
                width={200}
              />
              <Table.Column
                title="描述"
                dataIndex="description"
                width={200}
              />
              <Table.Column
                lock='right'
                title="操作"
                width={180}
                cell={this.renderOperations}
              />
            </Table>
          </div>
          <div style={styles.paginationContainer}>
            <Pagination
              current={tableData.currentPage}
              pageSize={this.props.limit}
              total={tableData.totalCount}
              onChange={this.changePage}
              hideOnlyOnePage={false}
            />
          </div>
        </IceContainer>
      </div>
    );
  }
}

const styles = {
  cardContainer: {
    padding: '0 0 20px 0',
  },
  titleCol: {
    display: 'flex',
    flexDirection: 'row',
  },
  titleText: {
    marginLeft: '10px',
    lineHeight: '20px',
  },
  operBtn: {
    display: 'inline-block',
    width: '16px',
    height: '16px',
    borderRadius: '999px',
    color: 'red',
    border: '1px solid red',
    background: '#ffffff',
    textAlign: 'center',
    cursor: 'pointer',
    lineHeight: '14px',
    marginLeft: '10px',
  },
  paginationContainer: {
    textAlign: 'right',
    paddingTop: '26px',
    paddingRight: '20px',
  },
  operationTableTitle: {
    fontSize: '18px',
    fontWeight: 'bold',
    fontColor: 'black',
    height: '32px',
    lineHeight: '30px',
    margin: '20px 0 20px 20px',
    paddingLeft: '12px',
    borderLeft: '4px solid rgb(102, 102, 102)',
  },
  addButton: {

  },
  userIdentity: {

  },
  link: {
    margin: '0 5px',
    color: 'rgba(49, 128, 253, 0.65)',
    cursor: 'pointer',
    textDecoration: 'none',
  },
  separator: {
    margin: '0 4px',
    display: 'inline-block',
    height: '12px',
    width: '1px',
    verticalAlign: 'middle',
    background: '#e8e8e8',
  },
  formItem: {
    display: 'flex',
    alignItems: 'center',
    margin: '20px 0px 20px 15px',
  },
  formLabel: {
    minWidth: '60px',
  },
};
